package me.leiusual.sharing.ui.shop.adapter

import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.layout_amount.view.*
import kotlinx.android.synthetic.main.view_holder_shop_business_apply_child.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.businesscondition.ProductOption
import me.leiusual.sharing.util.extension.setImageUrl
import me.leiusual.sharing.util.extension.spToPx
import me.leiusual.sharing.util.extension.toSpanned
import me.leiusual.sharing.widget.AmountView

/**
 * author: leiusual
 * create on: 2019-08-02
 * description:
 */
class ShopBusinessApplyChildViewHolder(
    override val containerView: View,
    private val changeListener: () -> Unit
) : RecyclerView.ViewHolder(containerView), LayoutContainer, View.OnClickListener, AmountView.Listener {

  private lateinit var productOption: ProductOption

  init {
    check_box.setOnClickListener(this)
    amount_view.listener = this
  }

  fun bind(productOption: ProductOption) {
    this.productOption = productOption

    // 选中
    check_box.isChecked = productOption.checked!!
    check_box.isEnabled = productOption.canModified

    // 图片
    image_view.setImageUrl(productOption.productImageUrl)

    // 名称
    text_view_product_name.text = productOption.productModelName

    // 价格
    val size = 10f.spToPx(containerView.context)
    val builder = StringBuilder()
    builder.append("""<font color="red">""")
    builder.append("""<size_$size>￥</size_$size>""")
    builder.append(productOption.coinAmount)
    builder.append("""</font>""")
    text_view_price.text = builder.toString().toSpanned()

    // 数量
    amount_view.minAmount = productOption.minPurchaseAmount
    amount_view.etAmount.setText(productOption.amount.toString())
    amount_view.maxAmount = productOption.sellingCount
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.check_box -> {
        productOption.checked = check_box.isChecked
        changeListener()
      }
    }
  }

  override fun onAmountClicked(amount: Int) {
    productOption.amount = amount
    changeListener()
  }
}